/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

/**
 *
 * @author wei
 */
@ManagedBean(name = "downloadPdf")
@SessionScoped
public class DownloadPDF {

    private StreamedContent file;
    private String path;


    public StreamedContent download() {
        if (path == null || path.isEmpty()) {
            System.out.println("path unspecified");
        }
        try {
            //check if file exist
            File javaFile = new File(path);
            boolean exists = javaFile.exists();
            if (!exists) {
                System.out.println("file not found: " + path);
                return null;
            }

            //name the pdf
            int index = path.lastIndexOf("/") < 0 ? path.lastIndexOf("\\") : path.lastIndexOf("/");
            String fileName = path.substring(index + 1);

            file = new DefaultStreamedContent(new FileInputStream(path),
                    "application/pdf", fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public StreamedContent getFile() {
        return file;
    }

    public void setFile(StreamedContent file) {
        this.file = file;
    }
    
}
